package com.pig4cloud.pig.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.customer.mapper.CustomerMapper;
import com.pig4cloud.pig.customer.service.CustomerService;
import com.pig4cloud.pig.customer.vo.TrCustomer;
import kotlin.jvm.internal.Lambda;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.regex.Pattern;

@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, TrCustomer> implements CustomerService {
	@Autowired
	private CustomerMapper customerMapper;
//	手机号正则表达式：以1开头，11位数字
	private static final String CUSTEL_REGEX = "^1[3-9]\\d{9}$";
	private static final Pattern CUSTEL_PATTERN = Pattern.compile(CUSTEL_REGEX);

	// 新增/修改时的手机号校验（统一逻辑）
	public R validateTel(TrCustomer customer, boolean isAdd) {
		String cusTel = customer.getCusTel();
		// 非空校验
		if (cusTel == null || cusTel.trim().isEmpty()) {
			return R.failed("手机号不能为空");
		}
		// 格式校验
		String trimmedTel = cusTel.trim();
		if (!CUSTEL_PATTERN.matcher(trimmedTel).matches()) {
			return R.failed("请输入有效的11位手机号");
		}
		// 唯一性校验（修改时排除自身ID）
		LambdaQueryWrapper<TrCustomer> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(TrCustomer::getCusTel, trimmedTel);
		if (!isAdd) { // 修改操作：排除当前客户ID
			queryWrapper.ne(TrCustomer::getCusId, customer.getCusId());
		}
		if (customerMapper.exists(queryWrapper)) {
			return R.failed("该手机号已被使用，请更换");
		}
		customer.setCusTel(trimmedTel); // 保存处理后的手机号
		return R.ok();
	}
	@Override
	public R addCustomer(TrCustomer customer) {
		R validateResult = validateTel(customer, true);
		if (!validateResult.isSuccess()) {
			return validateResult; // 校验失败直接返回
		}
		int rows = customerMapper.insert(customer);
		return rows > 0 ? R.ok("添加成功") : R.failed("添加失败");
	}

	@Override
	public Page<TrCustomer> pageCustomers(Page<TrCustomer> page, TrCustomer trCustomer) {
		return baseMapper.pageCustomers(page,trCustomer);
	}
	// 根据ID查询（带统计）
	@Override
	public TrCustomer getByIdWithCount(Long cusId) {
		return baseMapper.selectByIdWithCount(cusId);
	}
	// 新增：实现手机号校验接口（供前端实时校验）
	@Override
	public R<Boolean> checkTelExists(String cusTel, Long cusId) {
		if (cusTel == null || cusTel.trim().isEmpty()) {
			return R.ok(false); // 空值不视为存在
		}
		String trimmedTel = cusTel.trim();
		LambdaQueryWrapper<TrCustomer> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(TrCustomer::getCusTel, trimmedTel);
		if (cusId != null) { // 若传入ID，说明是修改操作，排除自身
			queryWrapper.ne(TrCustomer::getCusId, cusId);
		}
		boolean exists = customerMapper.exists(queryWrapper);
		return R.ok(exists); // 返回是否存在（true=已存在）
	}



}
